import 'dart:async';
import 'dart:math';
import 'dart:ui';

import 'package:flutter/material.dart';

//剪裁
class LearnClipPage extends StatefulWidget {
  @override
  _LearnClipPageState createState() => _LearnClipPageState();
}

class _LearnClipPageState extends State<LearnClipPage>
    with TickerProviderStateMixin {
  //保存创建集合
  List<BobbleBean> _list = [];
  //随机数据
  Random _random = Random(DateTime.now().microsecondsSinceEpoch);
  //最大半径
  double _maxRadius = 100.0;
  //最大速度
  double _maxSpeed = 0.7;
  //最大弧度
  double _maxAngle = 2.0 * pi;

  AnimationController _animationController;
  StreamController<double> _streamController = StreamController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    for (int i = 0; i < 20; i++) {
      BobbleBean _bobbleBean = BobbleBean();
      _bobbleBean.color = getRandomColor(_random);
      _bobbleBean.postion = Offset(-1, -1);
      _bobbleBean.radius = _random.nextDouble() * _maxRadius;
      _bobbleBean.speed = _random.nextDouble() * _maxSpeed;
      _bobbleBean.angle = _random.nextDouble() * _maxAngle;
      _list.add(_bobbleBean);
    }

    _animationController =
        AnimationController(duration: Duration(milliseconds: 500), vsync: this);

    _animationController.addListener(() {
      //流更新
      _streamController.add(0.0);
    });

    _animationController.repeat();
  }

  @override
  void dispose() {
    _streamController.close();
    _animationController.dispose();

    // TODO: implement dispose
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [Colors.orange, Colors.deepOrangeAccent],
          ),
        ),
        child: Stack(
          children: [
            //气泡
            _buildBobble(context),
            //高斯模糊
            _buildBlur(context),
          ],
        ),
      ),
    );
  }

/**********气泡**********/
  Widget _buildBobble(BuildContext context) {
    //使用Stream实现局部更xin
    return StreamBuilder(
        stream: _streamController.stream,
        builder: (context, bulder) {
          //自定义画板
          return CustomPaint(
            //自定义画手
            painter: ZdyBobblePainter(
              bobbleBeanArry: _list,
              random: _random,
            ),
            size: MediaQuery.of(context).size,
            // child: Container(
            //   height: MediaQuery.of(context).size.height,
            // ),
          );
        });
  }

  //高斯模糊
  Widget _buildBlur(BuildContext context) {
    return Padding(
      padding: EdgeInsets.fromLTRB(30, 100, 30, 0),
      child: Container(
        width: double.infinity,
        height: 50,
        child: ClipRRect(
          borderRadius: BorderRadius.all(Radius.circular(10)),
          child: BackdropFilter(
            filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
            child: Container(
              decoration: BoxDecoration(
                color: Colors.white24,
              ),
              child: Center(
                child: Text(
                  "高斯模糊",
                  style: TextStyle(fontSize: 20),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

//自定义绘画气泡
class ZdyBobblePainter extends CustomPainter {
  //创建画笔
  Paint _paint = Paint();
  //保存气泡集合
  List<BobbleBean> bobbleBeanArry;
  //随机数变量
  Random random;

  ZdyBobblePainter({this.bobbleBeanArry, this.random});

  @override
  void paint(Canvas canvas, Size size) {
    //每次绘制重新计算位置
    bobbleBeanArry.forEach((element) {
      //计算偏移
      var offset = calculateXY(element.speed, element.angle);
      //新坐标
      var dx = element.postion.dx + offset.dx;
      var dy = element.postion.dy + offset.dy;
      //x轴边界
      if (element.postion.dx < 0 || element.postion.dx > size.width) {
        dx = random.nextDouble() * size.width;
      }
      //y轴边界
      if (element.postion.dy < 0 || element.postion.dy > size.height) {
        dy = random.nextDouble() * size.height;
      }
      //更新位置
      element.postion = Offset(dx, dy);
    });

    //循环绘制气泡
    bobbleBeanArry.forEach((element) {
      //画笔颜色
      _paint.color = element.color;
      //绘制圆
      canvas.drawCircle(element.postion, element.radius, _paint);
    });
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}

//气泡属性配置
class BobbleBean {
  //位置
  Offset postion;
  //颜色
  Color color;
  //速度
  double speed;
  //角度
  double angle;
  //半径
  double radius;
}

//计算坐标
Offset calculateXY(double speed, double angle) {
  return Offset(speed * cos(angle), speed * sin(angle));
}

//获取随机透明白色
Color getRandomColor(Random random) {
  //0~255 0完全透明  255不透明
  //取值0～200
  int alp = random.nextInt(190) + 10;

  return Color.fromARGB(alp, 255, 255, 255);
}

//自定义剪裁
class ZdyClipper extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    Path path = Path();

    path.moveTo(0, 50);
    path.lineTo(0, size.height - 50);

    //二阶贝塞尔曲线
    //1
    path.quadraticBezierTo(0, size.height, 50, size.height);

    path.lineTo(size.width / 2.0 - 50 / 2.0, size.height);

    path.addArc(
        Rect.fromCenter(
            center: Offset(size.width / 2.0, size.height - 60),
            width: 50,
            height: 50),
        0,
        -2 * pi);

    //2
    // path.quadraticBezierTo(
    //     size.width, size.height, size.width, size.height - 50);

    return path;
  }

  @override
  bool shouldReclip(covariant CustomClipper<Path> oldClipper) {
    return true;
  }
}
